package com.nest.WorkNest.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lidroid.xutils.exception.HttpException;
import com.nest.WorkNest.R;
import com.nest.WorkNest.act.LoginAct;
import com.nest.WorkNest.act.ProductDetailAct;
import com.nest.WorkNest.api.XutilsPost;
import com.nest.WorkNest.data.OrderData;
import com.nest.WorkNest.tools.ParseUtils;
import com.nest.WorkNest.tools.Tool;

import java.util.ArrayList;
import java.util.HashMap;

public class OrderListAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();
    private onCheckedChanged listener;

    public OrderListAdapter(Context context, ArrayList<HashMap<String, String>> arrayList) {

        this.context = context;
        this.arrayList = arrayList;
    }


    @Override
    public int getCount() {
        return (arrayList != null && arrayList.size() == 0) ? 0 : arrayList.size();
    }

    @Override
    public Object getItem(int arg0) {
        return null;
    }

    @Override
    public long getItemId(int arg0) {
        return 0;
    }

    @Override
    public View getView(final int position, View currentView, ViewGroup arg2) {
        HolderView holderView;
        if (currentView == null) {
            holderView = new HolderView();
            currentView = LayoutInflater.from(context).inflate(R.layout.items_listview_placeorder,
                    null);
            holderView.chk_order_chooseitems = (CheckBox) currentView
                    .findViewById(R.id.chk_order_chooseitems);
            holderView.iv_order_pic = (ImageView) currentView.findViewById(R.id.iv_order_pic);
            holderView.tv_order_productname = (TextView) currentView
                    .findViewById(R.id.tv_order_productname);
            holderView.btn_order_delete = (Button) currentView.findViewById(R.id.btn_order_delete);
            holderView.btn_order_change = (Button) currentView.findViewById(R.id.btn_order_change);
            holderView.tv_order_price = (TextView) currentView.findViewById(R.id.tv_order_price);
            holderView.tv_order_number = (TextView) currentView.findViewById(R.id.tv_order_number);
            holderView.tv_order_pricesum = (TextView) currentView
                    .findViewById(R.id.tv_order_pricesum);
            currentView.setTag(holderView);
        } else {
            holderView = (HolderView) currentView.getTag();
        }
        if (arrayList.size() != 0) {
            float price = ParseUtils.string2float(arrayList.get(position).get("perPrice").toString());
            float sales = ParseUtils.string2float(arrayList.get(position).get("totalQuantity").toString());
            float pricesum = price * sales;
            holderView.tv_order_productname.setText(arrayList.get(position).get("productName").toString());
            holderView.tv_order_price
                    .setText("￥" + arrayList.get(position).get("perPrice").toString());
            holderView.tv_order_number
                    .setText("x" + arrayList.get(position).get("totalQuantity").toString());
            holderView.tv_order_pricesum.setText("￥" + pricesum);
            if (OrderData.editable) {
                holderView.btn_order_delete.setVisibility(View.VISIBLE);
                holderView.btn_order_change.setVisibility(View.VISIBLE);
                holderView.tv_order_pricesum.setVisibility(View.GONE);
                holderView.chk_order_chooseitems.setVisibility(View.GONE);
                holderView.btn_order_delete.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {

                        new AlertDialog.Builder(context).setTitle("删除提示").setMessage("你确定要删除吗?")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        arrayList.remove(position);
                                        loadDelOrder(arrayList.get(position).get("id"));
                                        notifyDataSetChanged();
                                    }

                                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).show();

                    }
                });
                holderView.btn_order_change.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, ProductDetailAct.class);
                        intent.putExtra("shoppingcart", 1);
                        intent.putExtra("id", arrayList.get(position).get("id"));
                        intent.putExtra("productId", arrayList.get(position).get("productId"));
                        context.startActivity(intent);
                    }
                });
            } else {
                holderView.btn_order_delete.setVisibility(View.GONE);
                holderView.btn_order_change.setVisibility(View.GONE);
                holderView.tv_order_pricesum.setVisibility(View.VISIBLE);
                holderView.chk_order_chooseitems.setVisibility(View.VISIBLE);
            }
            String imgUrl = arrayList.get(position).get("mainImage");
            if (!TextUtils.isEmpty(imgUrl)) {
                if (!imgUrl.substring(0, 1).equals("h") && !imgUrl.substring(0, 1).equals("H")) {
                    imgUrl = "http://" + imgUrl;
                }
            }
            Glide.with(context)
                    .load(imgUrl)
                    .centerCrop()
                    .placeholder(R.drawable.empty_photo)
                    .crossFade()
                    .into(holderView.iv_order_pic);

            holderView.chk_order_chooseitems
                    .setOnCheckedChangeListener(new OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton arg0, boolean choice) {
                            listener.getChoiceData(position, choice);
                        }
                    });

        }
        return currentView;
    }

    public class HolderView {
        CheckBox chk_order_chooseitems;
        ImageView iv_order_pic;
        TextView tv_order_productname, tv_order_price, tv_order_number, tv_order_pricesum;
        Button btn_order_delete, btn_order_change;
    }

    public interface onCheckedChanged {
        void getChoiceData(int position, boolean isChoice);
    }

    public void setOnCheckedChanged(onCheckedChanged listener) {
        this.listener = listener;
    }

    public void update(ArrayList<HashMap<String, String>> datalist) {
        this.arrayList = datalist;
        notifyDataSetChanged();
    }

    private void loadDelOrder(String id) {
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                if (Tool.getString(result, "resultCode").equals("0")) {
                    Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
                } else if (Tool.getString(result, "resultCode").equals("9001")) {
                    Toast.makeText(context, "token已过期，请重新登录", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(context, LoginAct.class);
                    context.startActivity(intent);
                } else {
                    Toast.makeText(context, Tool.getString(result, "MSG"), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void getDealException(HttpException httpException, String result) {

            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {

            }
        };
        xutilsPost.doPostDelShoppingCart(context, id, ioAuthCallBack);
    }
}
